<template>
  <view class="chat">
    <NavbarRight
      title="情绪分析"
      leftIconColor="#333333"
      bgColor="transparent"
      isBack
      :left="{ imageUrl: leftImageUrl, width: '48rpx' }"
    />
    <view class="background"> </view>
    <view class="content" id="content">
      <view class="content-inner" id="content-inner">
        <scroll-view
          class="msg-list"
          :style="{ height: scrollHeight + 'px' }"
          scroll-y="true"
          :scroll-top="scrollTop"
          :refresher-enabled="false"
          :scroll-into-view="scrollToView"
          @touchstart="touchstart"
          @touchend="touchend"
        >
          <!-- 加载历史数据waitingUI -->
          <view class="loading" v-if="isHistoryLoading">
            <view class="spinner">
              <view class="rect1"></view>
              <view class="rect2"></view>
              <view class="rect3"></view>
              <view class="rect4"></view>
              <view class="rect5"></view>
            </view>
          </view>
          <view class="head">
            <image :src="headIcon" mode="" class="head-logo"></image>
            <view class="head-title">{{ headMessage }}</view>
          </view>

          <view
            class="row"
            v-for="(row, index) in msgList"
            :key="row.scrollId"
            :id="row.scrollId"
          >
            <!-- 系统消息 -->
            <block v-if="row.type == 'system'">
              <view class="system">
                <!-- 文字消息 -->
                <view class="system-text" v-if="row.content">
                  <view class="system-text-content">{{ row.content }}</view>
                  <view class="arrow-right">
                    <up-icon
                      name="arrow-right"
                      color="#2979ff"
                      size="14"
                    ></up-icon>
                  </view>
                </view>
              </view>
            </block>
            <!-- 用户消息 -->
            <block v-if="row.type == 'user'">
              <!-- 自己发出的消息 -->
              <view class="my" v-if="row.flow == 'out'">
                <!-- 左-消息 -->
                <!-- <view class="create-time" v-if="row.sendTime">
                {{ row.sendTime }}
              </view> -->
                <view class="left">
                  <!-- 文字消息 -->
                  <view class="bubble">
                    <!-- <rich-text selectable :nodes="row.content"></rich-text> -->
                    <text
                      class="rich-text"
                      selectable="true"
                      user-select="true"
                      >{{ row.content }}</text
                    >
                  </view>
                </view>
                <!-- 右-头像 -->
                <view class="empty-right"> </view>
              </view>
              <!-- 别人发出的消息 -->
              <view class="other" v-if="row.flow == 'in'">
                <!-- 左-头像 -->
                <view class="other-left">
                  <image :src="evaluateIcon" class="other-avatar"></image>
                  <text>SLINA</text>
                </view>
                <!-- 右-用户名称-时间-消息 -->
                <view class="right">
                  <!-- <view class="create-time" v-if="row.sendTime">
                  {{ row.sendTime }}
                </view> -->
                  <!-- 文字消息 -->
                  <view class="bubble">
                    <!-- <rich-text selectable :nodes="row.content"></rich-text> -->
                    <text
                      class="rich-text"
                      :selectable="true"
                      :user-select="true"
                      >{{ row.content }}</text
                    >
                  </view>
                </view>
              </view>
            </block>
          </view>

          <view class="bubble" v-if="loading">
            <view class="loading ms-loading">
              <view class="spinner">
                <view class="rect1"></view>
                <view class="rect2"></view>
                <view class="rect3"></view>
                <view class="rect4"></view>
                <view class="rect5"></view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <!-- 底部输入栏 -->
    <view class="bottom-view bottom-footer">
      <view class="input-box">
        <view class="textbox">
          <textarea
            :disable-default-padding="true"
            fixed
            :auto-height="false"
            :adjust-position="true"
            :cursor-spacing="100"
            placeholder="欢迎向我提问~"
            placeholder-style="line-height:14px;height: 20px;font-size: 13px;"
            maxlength="250"
            class="input-textarea"
            @focus="inputFocus"
            @blur="inputLoseFocus"
            v-model="textMsg"
          />
        </view>
        <view class="send send-active" @click="sendText">
          <up-loading-icon
            text="发送中"
            size="13"
            textSize="13"
            color="#FFFFFF"
            textColor="#FFFFFF"
            v-if="loading"
          ></up-loading-icon>
          <text v-else>发送</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import NavbarRight from "@/components/navbar-right/index.vue";
import { onLoad, onReady, onShow, onUnload } from "@dcloudio/uni-app";
import { random_string } from "@/utils/common.js";

import { reactive, computed, ref, nextTick, watch } from "vue";
import { random } from "uview-plus";

import {
  getReciteInfo,
  getMessageListApi,
  sendMessageApi,
} from "@/api/records";

import useUserStore from "@/store/user.js";
import { storeToRefs } from "pinia";
import { showToast } from "../../../utils/common";
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore); // 响应式

const leftImageUrl = ref("/static/images/login/loginfanhui@3x.png");
const evaluateIcon = ref("/static/images/article/Group-43@3x.png");
const headIcon = ref("/static/images/article/Frame-52@3x.png");
const id = ref("");
const info = ref({});
const textMsg = ref("");
const loading = ref(false);
const windowHeight = ref(0);
const scrollHeight = ref(400);
const msgList = ref([]);
const headMessage = ref("");
const lastId = ref("0");

// watch(
//   () => msgList.value,
//   () => screenMsg(newVal, oldVal)
// );

onLoad((options) => {
  if (options && options.id) {
    id.value = options.id;
    getDetail();
  }
});

onUnload(() => {
  clearTimeout(timer);
});

onReady(() => {
  let systemInfo = uni.getSystemInfoSync();
  windowHeight.value = systemInfo.windowHeight;
  //.box获取class为box的元素，如果使用的id= 'box' 则使用'#box'
  nextTick(() => {
    uni
      .createSelectorQuery()
      .selectAll("#content-inner")
      .boundingClientRect((data) => {
        console.log("data[0].height", data[0].height);
        scrollHeight.value = data[0].height;
      })
      .exec();
  });
  if (id.value) {
    startPolling("first");
  }
});

onShow(() => {
  scrollTop.value = 9999999;
  let systemInfo = uni.getSystemInfoSync();
  if (systemInfo.windowHeight != windowHeight.value) {
    windowHeight.value = systemInfo.windowHeight;
    //.box获取class为box的元素，如果使用的id= 'box' 则使用'#box'
    nextTick(() => {
      uni
        .createSelectorQuery()
        .selectAll("#content-inner")
        .boundingClientRect((data) => {
          console.log("data[0].height", data[0].height);
          scrollHeight.value = data[0].height;
        })
        .exec();
    });
  }
});

const getDetail = async () => {
  try {
    let res = await getReciteInfo({
      id: id.value,
    });
    info.value = res.data;
    headMessage.value = res.data.emotion;
  } catch (e) {
    console.log(e);
    //TODO handle the exception
  }
};

let timer = null;
const startPolling = async () => {
  if (timer) {
    return false;
  }
  await getMessageList();
  timer = setTimeout(() => {
    clearTimeout(timer);
    timer = null;
    startPolling();
  }, 5000);
};

const getMessageList = async () => {
  try {
    let params = {
      id: id.value,
      lastid: lastId.value,
    };
    let res = await getMessageListApi(params);
    if (res.msgs && res.msgs.length) {
      res.msgs.map((item) => {
        item.type = "user";
        item.flow = item.fromid === userInfo.value.userid ? "out" : "in";
        item.scrollId = "scroll" + item.id;
      });
      msgList.value.push(...res.msgs);
      let last = msgList.value[msgList.value.length - 1];
      console.log("last============", last);
      lastId.value = last?.id || "0";
      screenMsg();
    }
  } catch (e) {
    console.log(e);
    //TODO handle the exception
  }
};

const scrollTop = ref(0);
const scrollToView = ref("");
const isHistoryLoading = ref(false);

// 接受消息(定位消息)
const screenMsg = () => {
  nextTick(() => {
    console.log("screenMsg");
    if (locked.value) {
      return false;
    }
    scrollToView.value =
      "scroll" +
      ((msgList.value[msgList.value.length - 1] &&
        msgList.value[msgList.value.length - 1].id) ||
        "");
    nextTick(() => {
      scrollTop.value += 1;
    });
  });
};
const createTextMessage = (msg) => {
  let id = msg.id || random_string();
  let scrollId = "scroll" + id;
  let message = {
    ...msg,
    id,
    scrollId,
    createTime: new Date(),
  };
  return message;
};

// 发送文字消息
const sendText = () => {
  if (!textMsg.value) {
    return false;
  }
  if (loading.value) {
    return false;
  }
  let msg = createTextMessage({
    flow: "out",
    type: "user",
    content: textMsg.value,
  });
  sendMsg(msg);
  postMessage(msg);
  textMsg.value = ""; //清空输入框
};
// 发送消息
const sendMsg = (msg) => {
  // this.$store.dispatch('message/Send_Message', msg)
  addTextMsg(msg);
  // 发送消息
};

// 添加文字消息到列表
const addTextMsg = (msg) => {
  msgList.value.push(msg);
  screenMsg();
};

const postMessage = async (msg) => {
  try {
    let res = await sendMessageApi({
      id: id.value,
      content: msg.content,
    });
    if (res.code == 0) {
      lastId.value = res.lastid || "";
    }
  } catch (error) {
    console.log(error);
  }
};

const textFilter = (text) => {
  if (text) {
    // var pattern = "\\\\n";
    // var target = "\n";
    // var reg = getRegExp(pattern, "g");
    // return text.replace(reg, target);
    return text.replace(/\n/g, "\n");
  }
  return "";
};
const locked = ref(false);
const touchstart = () => {
  locked.value = true;
};
const touchend = () => {
  locked.value = false;
};

const inputFocus = () => {
  inputLoseFocus.value = true;
};
const inputLoseFocus = () => {
  inputLoseFocus.value = false;
};
</script>

<style lang="scss" scoped>
@import "@/static/styles/scss/chat.scss";

.chat {
  position: relative;
  height: 100vh;
  background: #ffffff;
  display: flex;
  flex-direction: column;

  .background {
    width: 100%;
    height: 780rpx;
    top: 0;
    left: 0;
    position: absolute;
    background: linear-gradient(180deg, #90e4ed 0%, #ffffff 100%);
  }

  .content {
    height: 100%;
    overflow: auto;
    position: relative;
    z-index: 10;
    padding: 24rpx 32rpx;
    padding-bottom: 128rpx;
  }
}
</style>
